package com.ccsu.joysport.controller;


import com.ccsu.joysport.entity.Manager;
import com.ccsu.joysport.util.JwtUtil;
import com.ccsu.joysport.repository.ManagerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ccsu.joysport.entity.ClubOperator;
import com.ccsu.joysport.repository.ClubOperatorRepository;
import com.ccsu.joysport.entity.User;
import com.ccsu.joysport.repository.UserRepository;
import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("/ccsu/admin")
public class getManagerTokenController {

    @Autowired
    private ManagerRepository managerRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ClubOperatorRepository clubOperatorRepository;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/getToken")
    public ResponseEntity<?> getToken(@RequestParam String account, @RequestParam String password) {
        Optional<Manager> managerOptional = managerRepository.findByAccount(account);

        String role;
        if (managerOptional.isPresent() && managerOptional.get().getPassword().equals(password)) {
            role = managerOptional.get().getRole();
        } else {
            Optional<User> userOptional = userRepository.findByAccount(account);
            if (userOptional.isPresent() && userOptional.get().getPassword().equals(password)) {
                // 检查 club_operator 表
                List<ClubOperator> clubOperators = clubOperatorRepository.findByOperatorStudentId(account);
                if (!clubOperators.isEmpty()) {
                    role = "operator";
                } else {
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
                }
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
            }
        }

        String token = jwtUtil.generateToken(account);
        return ResponseEntity.ok(new AuthResponse(token, role));
    }

    // 内部类，用于封装token和role
    private static class AuthResponse {
        private String token;
        private String role;

        public AuthResponse(String token, String role) {
            this.token = token;
            this.role = role;
        }

        public String getToken() {
            return token;
        }

        public String getRole() {
            return role;
        }
    }
}
